import React from "react";
import styles from './index.less';
import { Modal, DatePicker, InputItem, Picker, Switch, Toast } from 'antd-mobile';
import ReactDOM from 'react-dom';
import SeModal from '@/components/searchEmployee';
import { getMastId } from '@/utils/tools';
import UserServices from '@/services/user';
import { requestSuccess, addHidden, removeHidden } from '@/utils/tools';
// 请求后返回值

class addTicketInfoModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true,
      message: props.message,
      content: props.content,
      success: props.success,
      cancel: props.cancel,
      datepickerActiveKey: '',
      datepickerVisible: false,
      orderNo: '',
      values: {
        traveller: '',
        transportation: '',
        fromCity: '',
        toCity: '',
        departureDateTime: '',//需要转换
        arrivalDateTime: '',//需要转换
        price: '',
        exceedStd: '',
        confirmFlag: '',
        describe: '',
        remark: ''
      }
    };
    window.cordovaBackEvents.push(() => {
      this.handleCancel();
    });
  }

  handleShowDatePicker = (activeKey) => {
    this.setState({
      datepickerActiveKey: activeKey,
      datepickerVisible: true
    })
  }

  handleFormatData = (data) => {
    const id = getMastId();

    return {
      ...id,
      dptrTime: global.moment(data.departureDateTime).format('HH:mm'),
      arrTime: global.moment(data.arrivalDateTime).format('HH:mm'),
      ticketInfo:{
        ...data,
        exceedStd: data.exceedStd ? 'YES':'NO',
        confirmFlag: data.confirmFlag ? 'YES':'NO',
        departTime: global.moment(data.departureDateTime).format('YYYY-MM-DD'),
        arriveTime: global.moment(data.arrivalDateTime).format('YYYY-MM-DD')
      }
    }
  }

  componentWillUnmount(){

  }

  componentDidMount(){
    addHidden()
  }

  handleSuccess = (e) => {
    const data = this.handleFormatData(this.state.values);
    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.saveTicketInfo(data).then(res => {
      if(requestSuccess(res)){
        this.setState({
          visible: false,
        });
        removeHidden();
        // res.data.mobileTicketInfo 是个数组
        this.state.success && this.state.success(res.data.mobileTicketInfo);
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
  }

  handleCancel = (e) => {
    removeHidden()
    // ReactDOM.unmountComponentAtNode(document.getElementById("addTicketInfoModal"))
    this.setState({
      visible: false,
    });
    // this.state.cancel && this.state.cancel();
  }

  handleSaveDatepickerValue = (date) => {
    if(this.state.datepickerActiveKey){
      this.onChange(global.moment(date).format('YYYY-MM-DD HH:mm').valueOf(), this.state.datepickerActiveKey);
      this.setState({
        datepickerVisible: false
      })
    }
  }

  onChange = (value, key) => {
    this.setState({
      values: {
        ...this.state.values,
        [key]: value
      }
    })
  }

  handleSelectedEmployee = (key)=>{
    SeModal.open({
      success: (result) => {
        this.setState({values: {
          ...this.state.values,
          [key]: result.employees
        }})
      },
      cancel: () => {

      }
    })
  }

  onChange = (value, key) => {
    this.setState({
      values: {
        ...this.state.values,
        [key]: value
      }
    })
  }

  handleSearch = () => {
    const id = getMastId(); //{traMastId: xx}

    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.getTicketInfoByCtrip({
      ...id,
      ticketInfo: {
        orderNo: this.state.orderNo
      }
    }).then(res => {
      if(requestSuccess(res)){
        console.log(res);
        this.setState({
          visible: false,
        });
        this.state.success && this.state.success('fromCtripSuccess');
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)
  }

  render() {
    return (
      <Modal
        visible={this.state.visible}
        className={styles.addTicketInfoModal}
      >
      <div className={styles.modalWrapper}>
        <DatePicker
          visible={this.state.datepickerVisible}
          mode='datetime'
          value={this.state.datepickerValue}
          onOk={this.handleSaveDatepickerValue}
          onDismiss={() => this.setState({ datepickerVisible: false })}
        />
      <div className={styles.info}>Ticket Info</div>
      <div className={styles.results}>
        <div className={styles.list}>
          <div className={styles.header}>Ctrip Order</div>
          <div className={styles.item}>
            <div className={styles.des}>*Ctrip Order No</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder="click input"
                value={this.state.orderNo}
                onChange={(value) => this.setState({orderNo: value})}
                ></InputItem>
            </div>
          </div>
          <div className={styles.searchBtn} onClick={this.handleSearch}>Get Detail From Ctrip</div>
        </div>
        <div className={styles.list}>
          <div className={styles.header}>*Non-Ctrip Order</div>
          <div className={styles.item}>
            <div className={styles.des}>*Traveller</div>
            <div className={styles.value} onClick={() => this.handleSelectedEmployee('traveller')}>
              {this.state.values.traveller || 'Select'}
            </div>
          </div>
          <Picker data={[{label: 'Plane', value: 'Plane'}, {label: 'Train', value: 'Train'}]} cols={1} onChange={(values) => this.onChange(values[0], 'transportation')}>
            <div className={styles.item}>
              <div className={styles.des}>*Transportation</div>
              <div className={styles.value}>
                {this.state.values.transportation || 'Select'}
              </div>
            </div>
          </Picker>
          <div className={styles.item}>
            <div className={styles.des}>*From（City）</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder="click input"
                value={this.state.values.fromCity}
                onChange={(value) => this.onChange(value, 'fromCity')}
                ></InputItem>
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.des}>*To（City）</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder="click input"
                value={this.state.values.toCity}
                onChange={(value) => this.onChange(value, 'toCity')}
                ></InputItem>
            </div>
          </div>
          <div className={styles.item} onClick={() => this.handleShowDatePicker('departureDateTime')}>
            <div className={styles.des}>*Departure DateTime</div>
            <div className={styles.value}>
              {this.state.values.departureDateTime || 'Select'}
            </div>
          </div>
          <div className={styles.item} onClick={() => this.handleShowDatePicker('arrivalDateTime')}>
            <div className={styles.des}>*Arrival DateTime</div>
            <div className={styles.value}>
              {this.state.values.arrivalDateTime || 'Select'}
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.des}>*Price（RMB）</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder="click input"
                value={this.state.values.price}
                onChange={(value) => this.onChange(value, 'price')}
                ></InputItem>
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.des}>*Exceeded Standard</div>
            <div className={styles.value}>
              <Switch checked={this.state.values.exceedStd} onChange={(value) => this.onChange(value, 'exceedStd')}></Switch>
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.des}>*Check Correct</div>
            <div className={styles.value}>
              <Switch checked={this.state.values.confirmFlag} onChange={(value) => this.onChange(value, 'confirmFlag')}></Switch>
            </div>
          </div>
          {/*

            <div className={styles.item}>
            <div className={styles.des}>*Describe</div>
            <div className={styles.value}>
            <InputItem
            clear
            placeholder="click input"
            value={this.state.values.describe}
            onChange={(value) => this.onChange(value, 'describe')}
            ></InputItem>
          </div>
        </div>
        */}

        <div className={styles.item}>
          <div className={styles.des}>*Remark</div>
          <div className={styles.value}>
            <InputItem
              clear
              placeholder="click input"
              value={this.state.values.remark}
              onChange={(value) => this.onChange(value, 'remark')}
              ></InputItem>
          </div>
        </div>
      </div>
      </div>
        <div className={styles.footerBtns}>
          <div onClick={this.handleSuccess}>Save</div>
          <div onClick={this.handleCancel}>Cancel</div>
        </div>
      </div>
      </Modal>
    );
  }
}

export default {
  open(params){
    let div = document.createElement('div');
    document.body.appendChild(div);
    ReactDOM.render(React.createElement(addTicketInfoModal, params), div);
  }
};
